<template>
  <el-dialog
  :title="'添加' + getTitlte"
  :visible.sync="addOptiondialogVisible"
  width="50%"
  @close="handleClose">
  
  <!-- 表单区域 -->
    <el-form :model="formOptionData" :rules="addOptionFormrules" 
    ref="addOptionFormRef" label-width="100px">
      <el-form-item :label="getTitlte" prop="attr_name">
        <el-input v-model="formOptionData.attr_name"></el-input>
      </el-form-item>
    </el-form>

  <!-- 按钮区域 -->
  <span slot="footer">
    <el-button @click="addOptiondialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="checkFun">确 定</el-button>
  </span>
  </el-dialog>
</template>

<script>
// 网络请求
import { postAddGoodOption } from '@/network/goodOptionRequest';

export default {
  data() {
    return {
      addOptiondialogVisible: false, // dialog开关
      infoObj: {}, // id、选中tab名
      formOptionData: { // 表单双向绑定
        attr_name: ''
      },
      addOptionFormrules: { // 验证规则
        attr_name: [{ required: true, message: '请输入参数名', trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleClose() { // 关闭dialog回调函数
       // 清除所有验证操作和内容
      this.$refs['addOptionFormRef'].resetFields();
    },
    checkFun() { // 确定按钮回调函数
      // 通过验证规则
      this.$refs['addOptionFormRef'].validate(val => {
        if (!val) {
          return this.$message.error('请按照提示填写完整');
        }
        this.addOptionRequst(); // 网络请求
        this.addOptiondialogVisible = false;
      })
    },
    openDialog(obj) {
      this.infoObj = obj;
      return this.addOptiondialogVisible = true;
    },
    async addOptionRequst() { // 添加参数网络请求
      const { meta } = await postAddGoodOption(this.infoObj.idArr[2], {
        attr_name: this.formOptionData.attr_name,
        attr_sel: this.infoObj.activeName
      })

      if (meta.status !== 201) {
        console.log(meta);
        return this.$message.error(meta.msg);
      }
      this.$bus.$emit('getGoodOptionDataListRequest'); // 刷新数据
      return this.$message.success(meta.msg);
    }

  },
  computed: {
    getTitlte() {
      return this.infoObj.activeName === 'many' ? '动态参数' : '静态参数';
    }
  },
  created() {
    this.$bus.$on('openGoodOptionDialog', infObj => this.openDialog(infObj));
  },
  destroyed() {
    this.$bus.$off('openGoodOptionDialog');
  }
}
</script>

<style>

</style>